package com.yu.thread5;

import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * Created by xiaolongyu on 15/3/20.
 */
public class SyncObject {
    public static void main(String[] args) {
        final DualSynch dualSynch = new DualSynch();
        new Thread(){
            @Override
            public void run() {
                dualSynch.f();
            }
        }.start();
        new Thread(){
            @Override
            public void run() {
                dualSynch.f1();
            }
        }.start();
        new Thread(){
            @Override
            public void run() {
                dualSynch.f3();
                dualSynch.f2();
            }
        }.start();
//        dualSynch.f2();
//        dualSynch.f3();

        new Thread(){
            @Override
            public void run() {
                dualSynch.g1();
            }
        }.start();
        new Thread(){
            @Override
            public void run() {
                dualSynch.g2();
            }
        }.start();
    }
}

class DualSynch{
    private Object syncObject = new Object();
    private Lock lock = new ReentrantLock();
    public synchronized void f(){
        for(int i = 0; i < 5; i ++){
            System.out.println("f()");
            Thread.yield();
        }
    }

    public synchronized void f1(){
        for(int i = 0; i < 5; i ++){
            System.out.println("f1()");
            Thread.yield();
        }
    }

    public void f2(){
        synchronized (this){
            for(int i = 0; i < 5; i ++){
                System.out.println("f2()");
                Thread.yield();
            }
        }
    }
    public void f3(){
        for(int i = 0; i < 5; i ++){
            System.out.println("f3()");
            Thread.yield();
        }
    }

    public void g1(){
        lock.lock();
        try{
            for(int i = 0; i < 5; i ++){
                System.out.println("g1()");
                Thread.yield();
            }
        } finally {
            lock.unlock();
        }
    }

    public void g2(){
        lock.lock();
        try{
            for(int i = 0; i < 5; i ++){
                System.out.println("g2()");
                Thread.yield();
            }
        } finally {
            lock.unlock();
        }
    }
}